package com.dk.filter;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.dk.result.Result;
import com.dk.result.ResultConstant;
import com.dk.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Set;

@Order(-1)
@Component
public class MESLoginFilter implements GlobalFilter {
    @Autowired
    private JwtUtil jwtUtil;

    @Value("#{'${gateway.exclusions.urls}'.empty?null:'${gateway.exclusions.urls}'.split(',')}")
    private Set<String> urls;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求头信息
        ServerHttpRequest request = exchange.getRequest();
        //获取访问路径
        String path = request.getURI().getPath();
        for (String url : urls) {
            if(antPathMatcher.match(url,path)){
                //路径匹配放过请求
                return chain.filter(exchange);
            }
        }
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");
        if (token == null || "".equals(token)) {
            return getVoidMono(exchange);
        }
        //如果存在token进行判断
        try {
            jwtUtil.parseJwt(token);
        } catch (Exception e) {
            return getVoidMono(exchange);
        }
        return chain.filter(exchange);
    }

    private Mono<Void> getVoidMono(ServerWebExchange exchange) {
        //获取响应
        ServerHttpResponse response = exchange.getResponse();
        //设置响应码
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //设置响应头编码
        response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
        //设置响应内容
        Result result = new Result(ResultConstant.TOKEN_CODE, ResultConstant.TOKEN_MESSAGE);
        byte[] bytes = JSONObject.toJSONBytes(result, SerializerFeature.WriteMapNullValue);
        DataBuffer wrap = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(wrap));
    }
}